;;; Guile-GCC --- Guile extension to GCC.               -*- coding: utf-8 -*-
;;; Copyright (C) 2012 Ludovic Courtès
;;;
;;; This file is part of Guile-GCC.
;;;
;;; Guile-GCC is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; Guile-GCC is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Guile-GCC.  If not, see <http://www.gnu.org/licenses/>.

(define-module (call-graph)
  #:use-module (gcc)
  #:use-module (gcc cgraph)
  #:use-module (srfi srfi-1))

(define call-graph-info-pass
  (make-pass "call-graph-info" GIMPLE_PASS
             (lambda ()
               (let ((n (cgraph-get-node (current-function-decl))))
                 (inform (decl-source-location (cgraph-node-decl n))
                         "~a callers, ~a callees"
                         (length (cgraph-node-callers n))
                         (length (cgraph-node-callees n))))

               ;; Nothing left to do.
               0)))

;; Register a pass after `*build_cgraph_edges', which is the one that builds
;; the cgraph nodes.
(register-pass "guile" call-graph-info-pass "*build_cgraph_edges"
               (pass-position after))

(define %output-file-name
  ;; Name of the file to store the `dot' output.  Honor
  ;; `-fplugin-arg-guile-dot-file'.
  (or (assoc-ref %plugin-arguments "dot-file")
      "call-graph.dot"))

;; Register a callback to be called after most of the optimization passes,
;; including inlining.
(register-callback "guile" PLUGIN_FINISH
                   (lambda ()
                     (call-with-output-file %output-file-name
                       (lambda (port)
                         (inform %unknown-location
                                 "dot output written to `~a'"
                                 %output-file-name)
                         (cgraph-nodes->dot (cgraph-nodes) port)))))
